import React, { Component } from 'react';
import IceContainer from '@icedesign/container';
import { Table, Button, Input, Grid, Form, Select, Message } from '@alifd/next';
import { ApiOfResourceGet, ApiOfResourceBindMetricGroups, ApiOfMetricGroupList } from '#/utils/coreApiDefine'
import MetricGroupPage from '#/pages/MetricGroup'

const { Row, Col } = Grid;

export default class BindMetricGroup extends Component {
    static displayName = 'BindMetricGroup';
    static propTypes = {};
    static defaultProps = {};

    constructor(props) {
        super(props);
        this.state = {
            resourceCode: this.props.code || this.props.match.params.code,
            availableMetricGroups: [],
            availableMetricGroupDS: [],
            reboundMetricGroups: [],
            selectedMetricGroupId: '',
        };
    }

    componentDidMount() {
        let that = this;
        ApiOfResourceGet(this.state.resourceCode).then(response => {
            let data = response.data;
            that.setState({
                reboundMetricGroups: data.metricGroups
            })
        })
    }

    renderMetricGroupConfig = (value, index, item) => {
        let that = this;
        if (!item.config) {
            return (
                <div></div>
            );
        } else {
            let config = JSON.parse(item.config);
            return (
                <div>
                    {Object.keys(config).map(function (k) {
                        return (
                            <dl key={k} style={styles.horizontal.dl}>
                                <dt style={styles.horizontal.dt}>{k}:</dt>
                                <dd style={styles.horizontal.dd}>{config[k]}</dd>
                            </dl>
                        );
                    })}
                </div>
            );
        }
    }

    // renderExecutionCycle = (value, index, item) => {
    //     return (
    //         <div>{item.executionCycle} 秒</div>
    //     );
    // }

    renderOper = (value, index, item) => {
        let that = this;
        return (
            <div>
                <Button onClick={() => this.onRemoveMetricGroup(item)} type="primary" text style={{ color: '#ff3000' }}>{item.dirty == 1 ? '撤销' : '移除'}</Button>
            </div>
        );
    }

    onRemoveMetricGroup = metricGroup => {
        let reboundMetricGroups = this.state.reboundMetricGroups
        let _metricGroup = reboundMetricGroups.find(item => item.id === metricGroup.id)
        reboundMetricGroups.splice(reboundMetricGroups.findIndex(item => item.id === _metricGroup.id), 1)
        this.setState({ reboundMetricGroups })
    }

    onAddMetricGroup = metricGroups => {
        let merged = [...metricGroups, ...this.state.reboundMetricGroups]
        if (merged.filter(it => it.usageType == 'COLLECT').length > 1
            || merged.filter(it => it.usageType == 'CONTROL').length > 1) {
            Message.show({
                type: 'error',
                title: '绑定指标组',
                duration: 6000,
                content: '每个设备最多只能绑定一个采集指标组和一个控制指标组'
            });
            return;
        }
        metricGroups.forEach(metricGroup => {
            let index = this.state.reboundMetricGroups.findIndex(value => value.id == metricGroup.id);
            if (index == -1) {
                this.state.reboundMetricGroups.push(metricGroup);
                this.setState({ reboundMetricGroups: this.state.reboundMetricGroups })
            }
        })

    }

    onBindMetricGroups = () => {
        let that = this;
        let reboundMetricGroupCodes = this.state.reboundMetricGroups.filter(item => item.dirty != 1).map(item => item.code);
        ApiOfResourceBindMetricGroups(this.state.resourceCode, reboundMetricGroupCodes)
            .then(() => {
                Message.success('指标组绑定成功!');
                this.props.history.push('/manage/device')
            })
    }

    setRowProps = (item, index) => {
        if (item.dirty === 1) {
            return {
                style: styles.willRemove,
            };
        } else if (item.dirty === 2) {
            return {
                style: styles.willAdd,
            };
        }
    }

    renderSummery = () => {
        let willAddCount = this.state.reboundMetricGroups.filter(item => item.dirty != 1).length;
        let willRemoveCount = this.state.reboundMetricGroups.length - willAddCount;
        let text = '待绑定：' + willAddCount + ' 个，' + '待移除：' + willRemoveCount + ' 个';
        return (
            <span>
                {text}
            </span>
        )
    }

    render() {

        let summery = this.renderSummery();
        let ActionBar =
            <div>
                <div style={styles.formItem}>
                    <div>
                        <Button onClick={this.onBindMetricGroups} type="primary" size="small" style={{ marginRight: 10 }} >提 交 </Button>
                    </div>
                    <div>
                        {summery}
                    </div>
                </div>
            </div>

        return (
            <IceContainer style={styles.container}>
                <Row wrap gutter="20" style={styles.formRow}>
                    <Col l="24">
                        {ActionBar}
                    </Col>
                </Row>
                <Table
                    dataSource={this.state.reboundMetricGroups}
                    hasBorder={false}
                    getRowProps={this.setRowProps}
                    style={{ padding: '0 20px 20px' }} >
                    <Table.Column width={280} title="名称" dataIndex="name" />
                    <Table.Column width={150} title="协议" dataIndex="protocol" />
                    {/*<Table.Column width={150} title="采集周期" dataIndex="executionCycle" cell={this.renderExecutionCycle} />*/}
                    <Table.Column
                        title="扩展配置"
                        dataIndex="rule"
                        cell={this.renderMetricGroupConfig}
                    />
                    <Table.Column
                        width={80}
                        title="操作"
                        cell={this.renderOper}
                    />
                </Table>
                <Row wrap gutter="20" style={styles.formRow}>
                    <Col l="24">
                        {ActionBar}
                    </Col>
                </Row>

                <div style={{ background: '#DCDCDC', padding: "10px 0" }}>
                    <MetricGroupPage forSelectUsage={true} match={this.props.match} onSelect={this.onAddMetricGroup} />
                </div>
            </IceContainer>
        );
    }
}

const styles = {
    container: {
        margin: '20px',
        padding: '0 0 20px',
    },
    title: {
        margin: '0',
        padding: '15px 20px',
        fonSize: '16px',
        textOverflow: 'ellipsis',
        overflow: 'hidden',
        whiteSpace: 'nowrap',
        color: 'rgba(0,0,0,.85)',
        fontWeight: '500',
        borderBottom: '1px solid #eee',
    },
    link: {
        margin: '0 5px',
        color: 'rgba(49, 128, 253, 0.65)',
        cursor: 'pointer',
        textDecoration: 'none',
    },
    separator: {
        margin: '0 3px',
        display: 'inline-block',
        height: '12px',
        width: '1px',
        verticalAlign: 'middle',
        background: '#e8e8e8',
    },
    pagination: {
        textAlign: 'right',
        marginRight: '20px',
    },
    editIcon: {
        color: '#2874D1',
        cursor: 'pointer',
    },
    horizontal: {
        dl: {
            marginTop: '3px',
            marginBottom: '3px',
        },
        dt: {
            float: 'left',
            width: '80px',
            overflow: 'hidden',
            clear: 'left',
            textAlign: 'right',
            textOverflow: 'ellipsis',
            whiteSpace: 'nowrap',
        },
        dd: {
            marginLeft: '100px',
        }
    },
    formItem: {
        display: 'flex',
        alignItems: 'center',
        margin: '10px 0',
    },
    formComponent: {
        minWidth: '300px',
    },
    formLabel: {
        minWidth: '70px',
    },
    willAdd: {
        background: '#dff0d8'
    },
    willRemove: {
        background: '#f2dede'
    },
    formRow: {
        padding: '10px 20px',
    },
    formItem: {
        display: 'flex',
        alignItems: 'center',
        margin: '10px 0',
    },
};